# -*- coding: utf-8 -*-
'''
#----------------------------------------------------------------------------------------
# 功能：导出Unity资源
#----------------------------------------------------------------------------------------
'''
import argparse
from flib.utils import *


# Unity操作
def UnityOp(project_path, execute_method, nc, argstring=""):
    consoleoutput = nc and "127.0.0.1:{0}".format(nc.get_port()) or ""
    unity_path = getenv("UNITY")
    logfile = project_path + "/unity.log"
    return execute('''"{0}"
        -projectPath "{1}"
        -executeMethod {2}
        -logFile "{3}"
        -quit -batchmode
        --auto-switch-target true
        --consoleoutput {4}
        {5}'''.format(unity_path,
                     project_path,
                     execute_method,
                     logfile,
                     consoleoutput,
                     argstring))

#####################################################################################################
# 导出美术资源
def export_arts(nc):
    ZLPrint("[session]", "开始导出美术资源")
    workspage = getenv("WORK_SPACE")
    artsdirname = getenv("ART_NAME")
    arts_project = os.path.join(workspage, artsdirname).replace('\\', '/')
    # 更新svn
    result = execute("svn update {0}".format(arts_project))
    if not result:
        return False
    for r in result:
        if r.find('   C ') != -1:
            f = r[5:]
            if os.path.exists(f):
                ZLPrint("[warning]", '''svn 更新遇到冲突：{0}'''.format(f))
                execute('''svn revert "{0}"'''.format(f))

    # 开始导出
    ZLPrint("[info]", "开始执行Unity命令导出资源")
    if not UnityOp(arts_project, "BatchExportRes.BatchExportArtRes", nc, "--platform " + getenv("platform")):
        return False
    ZLPrint("[session]", "结束导出美术资源")
    return True

# 导出界面资源
def export_ui(nc):
    ZLPrint("[session]", "开始导出界面资源")
    workspage = getenv("WORK_SPACE")
    program_project = os.path.join(workspage, getenv("PROJECT_NAME")).replace('\\', '/')
    unity_project = program_project + "/UnityProject"
    # 更新svn
    result = execute("svn update {}".format(program_project))
    if not result:
        return False
    for r in result:
        if r.find('   C ') != -1:
            f = r[5:]
            if os.path.exists(f):
                ZLPrint("[warning]", '''svn 更新遇到冲突：{0}'''.format(f))
                execute('''svn revert "{0}"'''.format(f))
    # 开始导出
    ZLPrint("[info]", "开始执行Unity命令导出资源")
    if not UnityOp(unity_project, "BatchExportRes.BatchExportUIPrefab", nc, "--platform " + getenv("platform")):
        return False
    ZLPrint("[session]", "结束导出界面资源")
    return True

# svn冲突回滚
def revert_art():
    ZLPrint("[info]", "回滚美术资源")
    workspage = getenv("WORK_SPACE")
    artsdirname = getenv("ART_NAME")
    arts_project = os.path.join(workspage, artsdirname).replace('\\', '/')
    work_dir = os.getcwd().replace("\\", "/").replace('\\', '/').decode("gbk")
    return exec_sh('''cd "{}" && svn cleanup && cd "{}" || exit 1'''.format(arts_project, work_dir)) and exec_sh('''cd "{}" && svn revert -R . && cd "{}" || exit 1'''.format(arts_project, work_dir))

def revert_program():
    ZLPrint("[info]", "回滚界面资源")
    workspage = getenv("WORK_SPACE")
    program_project = os.path.join(workspage, getenv("PROJECT_NAME")).replace('\\', '/')
    work_dir = os.getcwd().replace("\\", "/").replace('\\', '/').decode("gbk")
    revert_floder = ["Arts", "Shaders", "3rd", "Buildings", "Fonts", "Maps", "Scripts", "Terrain", "WLua", "XUPorter"]
    for d in revert_floder:
        if not exec_sh('''cd "{}" && svn cleanup && cd "{}" || exit 1'''.format(program_project + "/UnityProject/Assets/" + d, work_dir)):
            return  False
        if not exec_sh('''cd "{}" && svn revert -R . && cd "{}" || exit 1'''.format(program_project + "/UnityProject/Assets/" + d, work_dir)):
            return False
    return True


__TRY_COUNTLIMIT = 10
__TRY_COUNT__ = 0

def export_assets(nc, flag):
    global __TRY_COUNT__
    if flag == 0:
        if not export_arts(nc):
            __TRY_COUNT__ = __TRY_COUNT__ + 1
            return 1
        if not export_ui(nc):
            __TRY_COUNT__ = __TRY_COUNT__ + 1
            return 2
    elif flag == 1:
        if not export_arts(nc):
            __TRY_COUNT__ = __TRY_COUNT__ + 1
            return 1
    else:
        if not export_ui(nc):
            __TRY_COUNT__ = __TRY_COUNT__ + 1
            return 2
    ZLPrint("[info]", "资源导出成功")
    return 0

#####################################################################################################
#
#####################################################################################################
def platform(p):
    if p.lower() == "pc" or p.lower() == "win":
        return ["PC", "Win"]
    elif p.lower() == "android":
        return ["Android", "Android"]
    else:
        return ["IOS","IOS"]
def make_evn(args):
    setenv("platform", args.platform)
    setenv("UNITY", args.unity)
    setenv("WORK_SPACE", args.workspace)
    setenv("ART_NAME", args.art)
    setenv("PROJECT_NAME", "ElementUnity" + platform(getenv("platform"))[1])

def show_svninfo():
    ZLPrint("美术svn地址:")
    workspage = getenv("WORK_SPACE")
    artsdirname = getenv("ART_NAME")
    arts_project = os.path.join(workspage, artsdirname).replace('\\', '/')
    safe_execute('''svn info "{0}"'''.format(arts_project))
    ZLPrint("程序svn地址:")
    program_project = os.path.join(workspage, getenv("PROJECT_NAME")).replace('\\', '/')
    safe_execute('''svn info "{0}"'''.format(program_project))

def main():
    nc = nc_server()
    nc.start()

    global __TRY_COUNT__
    global __TRY_COUNTLIMIT
    result = 0
    while True:
        result = export_assets(nc, result)
        if result == 0:
            break
        if __TRY_COUNT__ >= __TRY_COUNTLIMIT:
            break
        # 尝试回滚
        if result == 1:
            revert_art()
        if result == 2:
            revert_program()
        # 再次尝试
        ZLPrint("[session]", "开始第{}次尝试".format(__TRY_COUNT__+1))
        result = export_assets(nc, result)

    time.sleep(2)
    nc.stop()
    nc.join()

    if 0 != result:
        exit(1)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--workspace", help="the workspace(eg. ElementUnityAndroid, arts)", type=str, required=True, default=getenv("SEVEN_WORKSPACE") or "")
    parser.add_argument("--svn-branch", help="the svn branch", type=str, default="trunk")
    parser.add_argument("--art", help="the path of unity.exe", type=str, default="art")
    parser.add_argument("--unity", help="the path of unity.exe", type=str, required=True, default=getenv("UNITY") or "")
    parser.add_argument("--platform", help="witch platform(eg. win(or pc)/android/ios)", type=str, default="win")
    args = parser.parse_args()
    make_evn(args)
    show_svninfo()
    main()